<?php

namespace app\store\task;

use app\store\service\GroupActivityService;
use think\facade\Db;
use yunwuxin\cron\Task;

class GroupActivityTask extends Task
{
    public function configure()
    {
        $this->everyMinute();
    }

    /**
     * 执行任务
     * @return mixed
     */
    protected function execute()
    {
        $activityList = Db::name('group_activity')
                        ->field('id,end_time,store_id,success_rule,fail_rule')
                        ->where('status',1)
                        ->withAttr('success_rule',function ($value){
                           return json_decode($value,true);
                        })->withAttr('fail_rule',function ($value){
                             return json_decode($value,true);
                        })->select();

        if (!$activityList->isEmpty()){
            foreach ($activityList as $v){

                $records =  GroupActivityService::getActivityRecord($v['id']);

                if ($v['end_time']<= time() && empty($records)){
                    Db::name('group_activity')->where('id',$v['id'])->update(['status'=>2]);
                    continue;
                }

                if ($v['end_time']<= time()){
                  $data =  GroupActivityService::finishGroupActivity($v,$records);
                  if (!empty($data)){
                        GroupActivityService::saveSuccessAwardQueue($data['user_id'],$data['success_gift']);
                        GroupActivityService::saveFailAwardQueue($data['user_ids'],$data['fail_gift']);
                        GroupActivityService::saveFailRefundQueue($data['store_id'],$data['group_orders']);
                  }
                }
            }
        }
    }


}